<?php
include('common_include.php');
include('validateSession.php');

/* Information for add operation */
$country = $_POST["country"];
$address = $_POST["address"];
/* end add operation */

$operation = $_POST["operation"];
$deleteID = $_POST["deleteID"];
$factoryArr = $_POST["factory"];

//var_dump($_POST);
//var_dump($factoryArr);

$dao = new SQLitePersistence();

if ($operation == 'Add' && $country != '' && $address != '') {
	try {
		$factoryObj = new Factory();
		$factoryObj->setFactoryCountry($country);
		$factoryObj->setFactoryAddress($address);
		$dao -> saveNewFactory($factoryObj);
		header("Location: factory_update.php");
	} catch (Exception $e) {
		header("Location: factory_update.php?error=Save Factory Failed.");
	}
} else if ($operation == 'Delete' && $deleteID != '') {
	try {
		$dao -> deleteFactory($deleteID);
		header("Location: factory_update.php");
	} catch (Exception $e) {
		header("Location: factory_update.php?error=Delete Factory Failed");
	}
} else if ($operation == 'Update' && sizeof($factoryArr) > 0) {
	try {
		for ($i=0; $i < sizeof($factoryArr); $i++) {
			$factoryObj = new Factory();			
			$factoryObj->setFactoryId($factoryArr[$i]['factoryID']);
			$factoryObj->setFactoryCountry($factoryArr[$i]['country']);
			$factoryObj->setFactoryAddress($factoryArr[$i]['address']);
			$factoryObj->setFactorySeq($factoryArr[$i]['factorySeq']);
			$dao -> updateFactoryObj($factoryObj);
			unset($factoryObj);
		}
		header("Location: factory_update.php");
	} catch (Exception $e) {
		header("Location: factory_update.php?error=Update Factory Failed");
	}
} else {
	Logger::logInfo("Javascript Injection disabled");
}

unset($dao);
?>